// pages/register/register.js

const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

import { request } from "../../utils/request";

Page({

  /**
   * 页面的初始数据
   */
  data: {
    redirect: "",
    avatarUrl: defaultAvatarUrl,
    avatarBase64: "",
    nickname: ""
  },
  onChooseAvatar(e) {
    const { avatarUrl } = e.detail;
    this.setData({ avatarUrl });

    // 读取文件为 Base64
    const fs = wx.getFileSystemManager();
    fs.readFile({
      filePath: avatarUrl,
      encoding: 'base64',
      success: res => {
        // 拼上前缀
        const base64WithPrefix = `data:image/jpeg;base64,${res.data}`;
        this.setData({ avatarBase64: base64WithPrefix });
      },
      fail: err => {
        console.error("读取头像失败", err);
      }
    });
  },
  // 点击注册按钮
  register() {
    wx.login({
      success: (loginRes) => {
        if (!loginRes.code) {
          wx.showToast({ title: "登录失败，请重试", icon: "none" });
          return;
        }

        const postData = {
          nickname: this.data.nickname,
          avatar: this.data.avatarUrl,
          avatarBase64: this.data.avatarBase64,
          code: loginRes.code
        };

        request({ url: "user/register", method: "POST", data: postData })
          .then(() => {
            wx.showToast({ title: "注册成功", icon: "success" });
            wx.reLaunch({
              url: this.data.redirect,
            });
          })
          .catch(err => console.error("注册失败", err));
      },
      fail: (err) => {
        wx.showToast({ title: "wx.login失败，请检查网络", icon: "none" });
        console.error(err);
      }
    });
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let redirectUrl = "/pages/my/my"; // 默认值
  
    if (options.redirect && options.redirect !== "undefined" && options.redirect !== "null") {
      const decoded = decodeURIComponent(options.redirect);
      if (decoded && decoded !== "undefined" && decoded !== "null") {
        redirectUrl = decoded;
      }
    }
  
    this.setData({
      redirect: redirectUrl
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})